package com.cy.jxc.realm;

import com.cy.jxc.dao.UserShiroDao;
import com.cy.jxc.entity.Role;
import com.cy.jxc.entity.User;
import com.cy.jxc.service.impl.LoginServiceImpl;
import com.cy.jxc.utils.ApplicationContextUtils;
import com.cy.jxc.vo.UserRoleVo;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

public class MyRealm  extends AuthorizingRealm {
//   授权
    @Autowired
    UserShiroDao userShiroDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("1111");
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("授权认证"+primaryPrincipal);
        UserRoleVo userRoleVo = userShiroDao.findRoleByUserName(primaryPrincipal);
        List<Role> roles = userRoleVo.getRoles();
        if (!CollectionUtils.isEmpty(roles)){
            SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
            for (Role role : roles) {
                System.out.println(role.getRolename());
                simpleAuthorizationInfo.addRole(role.getRolename());
            }
            return simpleAuthorizationInfo;
        }
        return null;
    }

//    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        System.out.println("principal:"+principal);
        LoginServiceImpl loginServiceImpl = (LoginServiceImpl) ApplicationContextUtils.getBean("loginServiceImpl");
        System.out.println(loginServiceImpl);
        User userByname = loginServiceImpl.findUserByname(principal);
        if (!ObjectUtils.isEmpty(userByname)){
            SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(userByname.getUsername(),userByname.getPassword(),this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
